package servlet;

import bean.Car;
import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import service.CarService;
import utils.PageUtil;
import utils.ResultVo;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
@WebServlet("/car")
public class CarServlet extends BaseServlet{
    CarService cs = new CarService();
    ResultVo vo = null;
    //分页查询功能
    public void findByPage(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        //从页面获取当前页
        String currentPage = req.getParameter("currentPage");
        //从页面获取页容量
        String pageSize = req.getParameter("pageSize");
        int totalCount = cs.getTotalCount();
        //创建分页查询工具类对象
        PageUtil pu = new PageUtil(totalCount,Integer.parseInt(pageSize),currentPage);
        List<Car> list = cs.findByPage(pu);
        pu.setList(list);
        vo = new ResultVo(200,"查询成功",pu);
        String s = JSON.toJSONString(vo);
        resp.getWriter().print(s);
    }
    //添加方法
    public void addCar(HttpServletRequest req,HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException, IOException {
        //获取页面数据
        Map<String, String[]> map = req.getParameterMap();
        Car car = new Car();
        BeanUtils.populate(car,map);
        //调用service层添加方法
        int row = cs.addCar(car);
        if(row>0){
            vo = new ResultVo(200,"添加成功",row);
        }else{
            vo = new ResultVo(500,"添加失败",row);
        }
        //转json格式
        String s = JSON.toJSONString(vo);
        //响应给页面
        resp.getWriter().print(s);
    }
}
